package com.xpgk.xpsoft.index;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.common.kit.PubKit;
import com.xpgk.common.tools.ToolCache;
import com.xpgk.model.FrmUser;
import com.xpgk.xpsoft.common.XPSoftService;
import com.xpgk.xpsoft.constants.XPSoftConstant;
import com.xpgk.xpsoft.department.DepartmentService;
import com.xpgk.xpsoft.user.UserService;

public class IndexService extends XPSoftService {

	static private List<Kv> AddMenu(Kv parant, List<Record> records) {
		boolean bFirst = false;
		if (parant == null) {
			bFirst = true;
			parant = Kv.by("id", "0").set("node", "").set("name", "主菜单").set("parentId", "0").set("url", "").set("icon", "").set("order", 1).set("isHeader", 1).set("childMenus", "");
		}
		String strNode = parant.getStr("node");
		int nNodeLen = strNode.length();
		List<Record> subRecords = new ArrayList<Record>();
		for (Iterator<Record> iterator = records.iterator(); iterator.hasNext();) {
			Record record = (Record) iterator.next();
			String t = record.getStr("node");
			if (t.length() == nNodeLen + 2 && t.substring(0, nNodeLen).equals(strNode))
				subRecords.add(record);
		}
		List<Kv> mm = new ArrayList<Kv>();
		for (Iterator<Record> iterator = subRecords.iterator(); iterator.hasNext();) {
			Record record = (Record) iterator.next();
			Kv kv = Kv.by("id", record.get("id")).set("name", record.get("name")).set("parentId", parant.get("id")).set("icon", PubKit.ifNull(record.get("icon"), "")).set("order", 1).set("isHeader", 0).set("childMenus", "").set("node", record.get("node"));
			String url = record.get("url");
			if (url == null)
				kv.set("url", "");
			else {
				if (url.startsWith("/"))
					kv.set("url", url.substring(1));
				else
					kv.set("url", url);
			}
			AddMenu(kv, records);
			mm.add(kv);
		}
		parant.set("childMenus", mm);
		if (bFirst) {
			List<Kv> m = new ArrayList<Kv>();
			m.add(parant);
			return m;
		}
		return mm;
	}

	// 得到用户菜单列表
	static public List<Kv> GetUserMenu(int userID) {
		List<Kv> menu = ToolCache.get(XPSoftConstant.cacheKey_UserMenu(userID));
		if (menu == null) {
			List<Record> records = Db.find(Db.getSqlPara("xpSoftIndex.findMenuByUserID", Kv.by("USERID", userID)));
			menu = AddMenu(null, records);
			ToolCache.set(XPSoftConstant.cacheKey_UserMenu(userID), menu);
		}
		return menu;
	}

	static public String GetUserDeptName(int userID) {
		FrmUser user = UserService.getUser(userID);
		if (user == null)
			return null;
		return DepartmentService.getDeptName(user.getDEPARTMENTID());
	}

}
